package server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;


public class RequestProcessorV extends Thread {
    private Socket socket;

    private MyMapper myMapper;

    private String webappsPath;

    public RequestProcessorV(Socket socket, MyMapper myMapper, String webappsPath) {
        this.socket = socket;
        this.myMapper = myMapper;
        this.webappsPath = webappsPath;
    }


    @Override
    public void run() {

        try{
            InputStream inputStream = socket.getInputStream();

            //封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            //通过myMapper处理当前的请求

            // 获取当前请求的host及url
            String host = request.getHost();
            String url = request.getUrl();
            // 获取所有配置的servlet信息
            Map<String, MyHost> hostMap = myMapper.getHostMap();

            // 在hostMap中查询与当前请求具有相同host的信息
            MyHost myHost = hostMap.get(host);
            if (myHost != null){
                String webName = url.split("/")[1];

                Map<String, MyContext> contextMap = myHost.getContextMap();
                MyContext myContext = contextMap.get(webName);
                // 判断是否含有当前webapp
                if (myContext != null){
                    String servletUrl = "/" + url.split("/")[2];
                    Map<String, MyWrapper> wrapperMap = myContext.getWrapperMap();
                    if (wrapperMap.get(servletUrl) == null){
                        // 静态资源处理
                        response.outputHtml(webappsPath+request.getUrl());
                    }else {
                        // 动态资源处理
                        MyWrapper myWrapper = wrapperMap.get(servletUrl);
                        HttpServlet httpServlet = myWrapper.getServlet();
                        httpServlet.services(request,response);
                    }
                    response.outputHtml(request.getUrl());
                    socket.close();

                }else {
                    System.out.println("未找到对应项目");
                    response.outputHtml(webappsPath+"404");
                    return;
                }


            }else {
                System.out.println("未找到虚拟机");
                response.outputHtml(webappsPath+"404");
                return;
            }



        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
